package biz.tekeye.scanbarcode;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;

import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Main extends Activity {
	final Context context = this;

	public static String[] Regex(String input) {
		
		// using Pattern split() method
		Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);
		// Matcher matcher = pattern.matcher('ABcabdAb');
		pattern = Pattern.compile("\\W");
		String[] words = pattern.split(input);
		//for (String s : words) {
			//System.out.println("Split using Pattern.split(): " + s);
		//}
		return words;
	
	}
	public static enum NetStatus {
        NONET, FAULTYURL, NETOK, CONN_MISSING, FAIL
}

public static NetStatus checkNet() {
        
       
        // is the server reachable?
        try {
                URL url = new URL("http://192.168.182.1/android_connect/get_product_details.php");

                HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                urlc.setConnectTimeout(1000 * 5); // Timeout is in seconds
                urlc.connect();
                if (urlc.getResponseCode() == 200) {
                        //http response is OK
                        return NetStatus.NETOK;
                }else return NetStatus.FAIL;
                
        } catch (MalformedURLException e1) {
                return NetStatus.FAULTYURL;
        } catch (IOException e) {
                return NetStatus.NONET;
        }
}

	public boolean run(String input) {
		final JSONParser jsonParser = new JSONParser();
		final String pid;
		pid =input ;
		// single product url
		
		if (checkNet()!=NetStatus.FAIL)
		{
		final String url_product_detials = "http://192.168.182.1/android_connect/get_product_details.php";
		// JSON Node names
		final String TAG_SUCCESS = "success";
		final String TAG_PRODUCT = "product";
		final String TAG_PID = "pid";
		final String TAG_NAME = "name";
		final String TAG_PRICE = "price";
		final String TAG_UNIT = "unit";
		final String TAG_DESCRIPTION = "description";
		// Check for success tag
		int success;
		
		try {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("pid", pid));

			// getting product details by making HTTP request
			// Note that product details url will use GET request
			JSONObject json = jsonParser.makeHttpRequest(url_product_detials,
					"GET", params);

			// check your log for json response
			Log.d("Single Product Details", json.toString());

			// json success tag
			success = json.getInt(TAG_SUCCESS);
			if (success == 1) {
				// successfully received product details
				JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON
																		// Array

				// get first product object from JSON Array
				JSONObject product = productObj.getJSONObject(0);

				// product with this pid found
				// Edit Text

				TextView tvID = (TextView) findViewById(R.id.tvID);
				TextView tvPrice = (TextView) findViewById(R.id.tvPrice);
				TextView tvUnit = (TextView) findViewById(R.id.tvUnit);
				TextView tvDesc = (TextView) findViewById(R.id.tvDesc);
				// display product data in EditText
				tvID.setText(product.getString(TAG_NAME));
				tvPrice.setText(product.getString(TAG_PRICE));
				tvUnit.setText(product.getString(TAG_UNIT));
				tvDesc.setText(product.getString(TAG_DESCRIPTION));
				return true;

			} else {
				// product with pid not found
				Toast toast = Toast.makeText(getApplicationContext(), "Invalid product in database! Check again...",
	                      Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER|Gravity.LEFT, 0, 0);
				toast.show();
				return true;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		}else
		{
			final Toast toast = Toast.makeText(getApplicationContext(), "No Connection To Server! Check again...",
                    Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER|Gravity.LEFT, 0, 0);
			toast.show();
			Handler handler = new Handler();
	        handler.postDelayed(new Runnable() {
	           @Override
	           public void run() {
	               toast.cancel(); 
	           }
	    }, 2000);
			return false;
		}
		return true;
		
	}

	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		HandleClick hc = new HandleClick();
		HandleClick1 hc2 = new HandleClick1();
		findViewById(R.id.butQR).setOnClickListener(hc);
		findViewById(R.id.butProd).setOnClickListener(hc);
		findViewById(R.id.butOther).setOnClickListener(hc);
		findViewById(R.id.About).setOnClickListener(hc2);
	}

	private class HandleClick implements OnClickListener {
		public void onClick(View arg0) {
			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
			switch (arg0.getId()) {
			case R.id.butQR:
				intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
				break;
			case R.id.butProd:
				intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
				break;
			case R.id.butOther:
				intent.putExtra("SCAN_FORMATS",
						"CODE_39,CODE_93,CODE_128,DATA_MATRIX,ITF");
				break;

			}
			     
			
			
			startActivityForResult(intent, 0); // Barcode Scanner to scan for us

			
		
		}
	}

	private class HandleClick1 implements OnClickListener {
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.About: {
				
				// custom dialog
				final Dialog dialog = new Dialog(context);
				dialog.setContentView(R.layout.custom);
				dialog.setTitle("About QR_HoaQua...");

				// set the custom dialog components - text, image and button
				TextView text = (TextView) dialog.findViewById(R.id.text);
				text.append("This is Project Android using QR Code.!");
				text.append("\nYou can scan to show the true value (price) of vegetable.");
				text.append("\nAny contact: VoTienAn - Email: nguoitinh.cuaanh.12@gmail.com.");
				text.append("\nTeam: Vo Tien An - Truong Cong Hau - Tran Cong Hau");
				text.append("\nCopyright by Team - 2013");
				ImageView image = (ImageView) dialog.findViewById(R.id.image);
				image.setImageResource(R.drawable.qr_hoaqua);

				Button dialogButton = (Button) dialog
						.findViewById(R.id.dialogButtonOK);
				// if button is clicked, close the custom dialog
				dialogButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});

				dialog.show();

			}
				break;
			}
		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0) {
		
			
			TextView tvStatus = (TextView) findViewById(R.id.tvStatus);
			TextView tvResult = (TextView) findViewById(R.id.tvResult);
			TextView tvID = (TextView) findViewById(R.id.tvID);
			TextView tvPrice = (TextView) findViewById(R.id.tvPrice);
			TextView tvDesc = (TextView) findViewById(R.id.tvDesc);
			if (resultCode == RESULT_OK) {
				tvStatus.setText(intent.getStringExtra("SCAN_RESULT_FORMAT"));
				//tvResult.setText(intent.getStringExtra("SCAN_RESULT"));
				if (Regex(intent.getStringExtra("SCAN_RESULT"))!=null)
				{
				run(Regex(intent.getStringExtra("SCAN_RESULT"))[1]);				
				tvResult.setText("===Information About Your Product===");
				tvResult.append("\n"+Regex(intent.getStringExtra("SCAN_RESULT"))[2]+": ");
				
				tvResult.append(Regex(intent.getStringExtra("SCAN_RESULT"))[3]+"\n");
				tvResult.append(Regex(intent.getStringExtra("SCAN_RESULT"))[4]+": ");
				tvResult.append(Regex(intent.getStringExtra("SCAN_RESULT"))[5]+"\n");
				tvResult.append(Regex(intent.getStringExtra("SCAN_RESULT"))[6]+": ");
				tvResult.append(Regex(intent.getStringExtra("SCAN_RESULT"))[7]+"\n");
				tvResult.append("===Ready Scan Another===");
				} else
				{
					final Toast toast = Toast.makeText(getApplicationContext(), "Wrong Data Input! CHECK AND Scan Again...",
	                    Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER|Gravity.LEFT, 0, 0);
				toast.show();
				Handler handler = new Handler();
		        handler.postDelayed(new Runnable() {
		           @Override
		           public void run() {
		               toast.cancel(); 
		           }
		    }, 2500);
				}
				// intent.putExtras(EditProductActivity.class);
				
				
			} else if (resultCode == RESULT_CANCELED) {
				tvStatus.setText("Press a button to start a scan.");
				tvResult.setText("Scan cancelled.");
				tvID.setText("Product Name");
				tvPrice.setText("Price Here");
				tvDesc.setText("Description Here");

			}
		}
	}
}